<template>
  <el-dialog v-model="addNoticeVisible" :title="noticeId === 0 ? '公告创建' : '公告编辑'" width="600">
    <el-form ref="formRef" style="max-width: 600px" :model="formCustom" status-icon :rules="rules" label-width="auto">
      <el-form-item label="标题" prop="name">
        <el-input v-model="formCustom.name" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-select v-model="formCustom.level" placeholder="请选择">
          <el-option v-for="item in levelOptions" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="公告文件" prop="file_name">
        <el-input
          v-model="formCustom.file_name"
          type="text"
          :disabled="true"
          autocomplete="off"
          placeholder="请选择pdf文件上传"
        />
        <el-upload
          class="upload-demo"
          action="#"
          multiple
          accept=".pdf"
          ref="uploadRef"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :limit="1"
          :http-request="uploadExcel"
          :on-exceed="handleExceed"
          :on-success="excelUploadSuccess"
          :on-error="excelUploadError"
        >
          <el-button type="primary">
            上传pdf文件<el-icon class="el-icon--right"><Upload /></el-icon>
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit(formRef)">确定</el-button>
        <el-button @click="closeDialog()">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AddOrEditRole">
import { ref, reactive } from "vue";
import { createNotice, uploadPdfApi, modifyNotice } from "@/api/modules/sysManagement/noticeManagement";
import type { ElUpload, FormInstance, FormRules } from "element-plus";
import { ElNotification, UploadRequestOptions, ElMessage, ElMessageBox } from "element-plus";
import { Notice } from "@/api/interface/noticeManagement";
import type { UploadProps } from "element-plus";
const formRef = ref<FormInstance>();
let noticeId: any = 0;
const formCustom = reactive({
  name: "",
  level: "",
  file_link: "",
  file_name: ""
});
const rules = reactive<FormRules<typeof formCustom>>({
  name: [
    { required: true, message: "不能为空", trigger: "blur" },
    { required: true, message: "长度需为0~64个字符", min: 0, max: 64, trigger: "blur" }
  ],
  level: [{ required: true, message: "不能为空", trigger: "change" }],
  file_name: [{ required: true, message: "不能为空", trigger: "blur" }]
});
const uploadRef = ref<InstanceType<typeof ElUpload> | null>(null);
const levelOptions = reactive([
  {
    value: "EMERGENCY",
    name: "紧急"
  },
  {
    value: "IMPORTANT",
    name: "重要"
  },
  {
    value: "NORMAL",
    name: "普通"
  }
]);
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.org_id 的值，才会触发请求 proTable 数据
let loading = ref<boolean>(false);
const addNoticeVisible = ref<boolean>(false);
const addUploadFiles = ref<any>();
const openDialog = (data?: Notice.ResNoticeList) => {
  addNoticeVisible.value = true;
  noticeId = data ? data.id : 0;
  if (noticeId && data) {
    formCustom.name = data.name;
    formCustom.file_link = data.file_link;
    formCustom.file_name = data.file_name;
  } else {
    // 重置表单
    formCustom.name = "";
    formCustom.file_link = "";
    formCustom.file_name = "";
  }
  if (uploadRef.value && addUploadFiles.value) {
    uploadRef.value.clearFiles();
  }
  loading.value = false;
};
const closeDialog = () => {
  addNoticeVisible.value = false;
};

// emit
const emit = defineEmits<{
  refresh: [];
}>();

const submit = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (noticeId === 0) {
    // 创建
    const { data } = await createNotice(formCustom);
    if (data) {
      ElMessage({
        type: "success",
        message: `操作成功!`
      });
      addNoticeVisible.value = false;
      // 重置表单
      formCustom.name = "";
      formCustom.file_link = "";
      formCustom.file_name = "";
      emit("refresh");
    }
  } else {
    const paramsObj = { ...formCustom };
    // 编辑
    const { data } = await modifyNotice(noticeId, paramsObj);
    if (data) {
      ElMessage({
        type: "success",
        message: `操作成功!`
      });
      addNoticeVisible.value = false;
      // 重置表单
      formEl?.resetFields();
      emit("refresh");
    }
  }
};

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

// 文件上传
const uploadExcel = async (param: UploadRequestOptions) => {
  let excelFormData = new FormData();
  addUploadFiles.value = param.file;
  excelFormData.append("file", param.file);
  const { data } = await uploadPdfApi(excelFormData)
    .then<any>()
    .catch(err => {
      ElNotification({
        title: "温馨提示",
        message: `${data["message"]}，请您重新上传！`,
        type: "error"
      });
      console.log(err);
      formCustom.file_link = "";
      formCustom.file_name = "";
    });
  if (data) {
    formCustom.file_link = data["link"];
    formCustom.file_name = data["name"];
  }
};
// 上传错误提示
const excelUploadError = () => {
  ElNotification({
    title: "温馨提示",
    message: `添加pdf文件失败，请您重新上传！`,
    type: "error"
  });
  formCustom.file_link = "";
  formCustom.file_name = "";
};

// 上传成功提示
const excelUploadSuccess = () => {
  ElNotification({
    title: "温馨提示",
    message: `添加添加pdf文件成功！`,
    type: "success"
  });
};

const handleExceed: UploadProps["onExceed"] = () => {
  ElNotification({
    title: "温馨提示",
    message: "最多只能上传一个文件！",
    type: "warning"
  });
};

const beforeRemove: UploadProps["beforeRemove"] = uploadFile => {
  return ElMessageBox.confirm(`更换文件${uploadFile.name} ?`).then(
    () => true,
    () => false
  );
};
defineExpose({
  openDialog,
  closeDialog
});
</script>
<style lang="scss" scoped>
.filter {
  width: 100%;
  height: 500px;
  overflow-y: auto;
  border: none;
  box-shadow: none;
}
.upload-demo {
  margin-top: 5px;
}
</style>
